package com.cn.servlet;

import java.io.IOException;
import java.util.List;
import java.util.Map;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.beanutils.BeanUtils;

import com.cn.domain.Product;
import com.cn.domain.User;
import com.cn.service.ProductCategoryService;
import com.cn.service.UserService;
import com.cn.service.impl.ProductCategoryServiceImpl;
import com.cn.service.impl.UserServiceImpl;
import com.cn.utils.JsonMapper;
import com.cn.utils.PageView;

@WebServlet("/SearchServlet")
public class SearchServlet extends HttpServlet {
	//这个名字用于所搜框中输入的字符
	private ProductCategoryService proCatService=new ProductCategoryServiceImpl();
	private JsonMapper binder=JsonMapper.nonDefaultMapper();
	@Override
	protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
		this.doGet(req, resp);
	}

	@Override
	protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
		//获取需要查询的名字进行模糊查询
		//System.out.println("开始所搜....");
		String name=req.getParameter("searchValue");
		System.out.println("name=="+name);
		//req.getSession().setAttribute("serValue", name);
		String type=req.getParameter("type");
		if("showProToDiv".equals(type)){
			//开始执行模糊查询
			if(name!=null&&!("".equals(name))){
				//开始查询
				List<Product> proList=proCatService.queryProByName(name);
				//开始转成json
				String json=binder.toJson(proList);
				System.out.println("json"+json);
				resp.getWriter().println(json);
				return;
			}
		}else{
			int currentPage=1;
			String pageNow=req.getParameter("pageNow");
			if(pageNow!=null){
				currentPage=Integer.valueOf(pageNow);
			}
			//System.out.println(pageNow+":currentPa=="+currentPage);
			//name="衣";
			//System.out.println("name2222=="+name);
			req.getSession().setAttribute("serValue", name);
			//开始执行模糊查询
			if(name!=null&&!("".equals(name))){
				//开始查询
				List<Product> recordList=proCatService.queryProByName("HP_NAME",name, currentPage,PageView.PAGE_SIZE);
				int recordCount=proCatService.queryProCount(name).size();
				PageView pageModel=new PageView(currentPage, recordCount, recordList);
				//System.out.println("总页数="+pageModel.getPageCount());
				req.setAttribute("pageModel", pageModel);
				//System.out.println("点了button事件");
				//System.out.println("name中button333=="+name);
				req.getRequestDispatcher("/result_seek.jsp").forward(req, resp);
			}
		}
	}
}
